// 书写header部分的业务代码
import { Observer } from '../common/Observer'
import pxmu from 'pxmu';
let headPic = document.getElementById("headPic");
let username = document.getElementById("username");
let exit = document.getElementById("exit");
let login = document.getElementById("login");
let regist = document.getElementById("regist");
let userInfo = document.getElementById("userInfo")
let loginandregist = document.getElementById("loginandregist")




// 登录按钮 
login.onclick = function () {
    console.log(123)
    // 改变hash
    location.hash = "login"
    // 通知登录模块显示出来
    Observer.emit("login-show");
    // 内容页面消失
    Observer.emit('content-hide')

}


// 注册按钮
regist.onclick = function () {
    // 通知注册模块显示出来
    Observer.emit("regist-show")
    // 改变hash
    location.hash = "regist"
    Observer.emit('content-hide')

}


async function getUserInfo() {
    // 发送请求   获取用户信息
    let res = await fetch("/guyun/getUserInfo?authrization=" + localStorage.getItem("token"))
    let { error, data: { headpic, nickname } } = await res.json();

    // 判断
    if (!error) {
        // 把右上角的登录和注册替换为 头像、用户名、退出
        loginandregist.classList.add("d-none")
        // 头像更换
        headPic.src = headpic;
        // 用户名(其实是昵称)
        username.innerHTML = nickname;
        userInfo.classList.remove("d-none");
        return;
    }
    loginandregist.classList.remove("d-none")
    userInfo.classList.add("d-none");


}

Observer.on("getUserInfo", getUserInfo)

Observer.emit("getUserInfo")

// 退出功能
exit.onclick = function () {
    localStorage.removeItem("token");
    pxmu.success('退出成功');
    Observer.emit("getUserInfo");
    location.href = '/'
}